﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Roton.Engine
{
    public class PhysicalFileSystem : IFileSystem
    {
        string path;

        /// <summary>
        /// Create a physical file system context.
        /// </summary>
        public PhysicalFileSystem(string path)
        {
            this.path = path;
        }

        /// <summary>
        /// Get the current directory.
        /// </summary>
        public string GetCurrentDirectory()
        {
            return path;
        }

        /// <summary>
        /// Retrieve directory list in current directory.
        /// </summary>
        public List<string> GetDirectories()
        {
            return Directory.GetDirectories(path)
                .Select(i => i.Split(new char[] { Path.DirectorySeparatorChar })
                    .LastOrDefault())
                    .Where(i => !string.IsNullOrWhiteSpace(i))
                    .ToList();
        }

        /// <summary>
        /// Retrieve file list in current directory.
        /// </summary>
        public List<string> GetFiles(string filter)
        {
            return Directory.GetFiles(path, filter ?? @"*")
                .Select(i => Path.GetFileName(i))
                .ToList();
        }

        /// <summary>
        /// Switch to a subdirectory.
        /// </summary>
        public void OpenDirectory(string relativeDir)
        {
            string newPath = Path.Combine(path, relativeDir);
            if (Directory.Exists(newPath))
                path = newPath;
        }

        /// <summary>
        /// Open a file.
        /// </summary>
        public Stream OpenFile(string relativeFile)
        {
            string newFile = Path.Combine(path, relativeFile);
            if (File.Exists(newFile))
            {
                byte[] fileData = File.ReadAllBytes(newFile);
                return new MemoryStream(fileData);
            }
            return null;
        }

        /// <summary>
        /// Save a file.
        /// </summary>
        public void SaveFile(string relativeFile, byte[] data)
        {
            File.WriteAllBytes(Path.Combine(path, relativeFile), data);
        }
    }
}
